<template>
  <el-dialog
    @open="mixinOpen"
    @close="handleClose"
    :title="title"
    :visible="dialogVisible"
    width="80%"
  >
    <el-form
      :model="postData"
      :rules="postRules"
      label-width="80px"
      label-position="left"
      ref="postForm"
    >
      <el-form-item prop="name" label="角色选择">
        <el-select v-model="postData.rid" @change="handleChange">
          <el-option
            v-for="item in roleOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="areaId" label="权限查看">
        <el-checkbox-group v-model="checkList">
          <el-checkbox
            v-for="item in authLists"
            :key="item.id"
            :label="item.id"
            disabled
            >{{ item.name }}</el-checkbox
          >
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button @click="submit" type="primary">提 交</el-button>
    </div>
  </el-dialog>
</template>

<script>
import postDialog from "../../../mixins/postDialog";
import axios from "axios";

export default {
  name: "postDialog",
  mixins: [postDialog],
  data() {
    return {
      postData: {
        rid: ""
      },
      postRules: {
        rid: [{ required: true, message: "请选择角色", trigger: "blur" }]
      },
      addUrl: "/api/userAndRole/userAndRole",
      authLists: [],
      checkList: [],
      roleOptions: []
    };
  },
  methods: {
    async initRoleOptions() {
      const {
        data: { errno, message, data }
      } = await axios.get("/api/role/role/all");
      if (!errno) {
        this.roleOptions = data;
      } else {
        this.$message({ type: "error", message });
      }
    },
    async mixinOpen() {
      await this.handleOpen();
      this.handleChange();
    },
    handleChange() {
      if (this.postData.rid) {
        const role = this.roleOptions.filter(
          item => item.id == this.postData.rid
        )[0];
        if (role.auth === "all") {
          this.checkList = this.authLists.map(item => +item.id);
        } else {
          this.checkList = role.auth.split(",").map(item => +item);
        }
      }
    }
  },
  async mounted() {
    const {
      data: { errno, message, data }
    } = await axios.get("/api/menu/menu/all");
    if (!errno) {
      this.authLists = data;
    } else {
      this.$message({ type: "error", message });
    }
    this.initRoleOptions();
  }
};
</script>

<style scoped></style>
